package com.rk.app.poll.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class PollView implements EntryPoint {

	private final PollServiceAsync pollingService = GWT.create(PollService.class);

	private Poll poll = null;

	/**
	 * Entry point method.
	 */
	public void onModuleLoad() {
		final String pollId = Window.Location.getParameter("id");
		if (pollId == null || pollId.trim().equals("")) {
			Window.alert("Provide poll id to view poll results.");
			Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
			return;
		}
		String uri = Window.Location.getPath();
		pollingService.getSignInURL(uri, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				Window.alert("Error Occured:-\n" + caught.getLocalizedMessage());
			}

			public void onSuccess(String result) {
				if (result != null && result.toLowerCase().indexOf("sign out") >= 0) {
					getPoll(pollId);
				} else {
					Window.alert("Please sign in to submit your vote.");
					Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
				}

			}

		});

	}

	private void getPoll(String pollId) {
		pollingService.getPoll(pollId, new AsyncCallback<Poll>() {

			public void onFailure(Throwable caught) {
				Window.alert("Error Occured:-\n" + caught.getLocalizedMessage());
			}

			public void onSuccess(Poll result) {
				if (result == null) {
					Window.alert("Poll does not exists.");
					Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
				} else if (result.getEndsOn().before(new Date())) {
					Window.alert("The poll is closed, you can't vote.");
					Window.Location.replace(Window.Location.getProtocol() + "/pollApp.html");
				} else {
					poll = result;
					initPollUI();
				}
			}

		});
	}

	private void initPollUI() {
		PollViewWidget pollViewWidget = new PollViewWidget(poll);
		RootPanel.get().add(pollViewWidget);
	}
}
